/*******************************************************************************
 * Copyright (c) 2014 Joel Thurlby.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Joel Thurlby - initial API and implementation
 ******************************************************************************/
package jat.xtext.gantt.validation

import jat.xtext.gantt.ganttText.GanttTextPackage
import jat.xtext.gantt.ganttText.Model
import jat.xtext.gantt.ganttText.Task
import jat.xtext.gantt.ganttText.WorkPackage
import jat.xtext.gantt.ganttText.WorkPackageResource
import org.eclipse.emf.common.util.EList
import org.eclipse.xtext.resource.XtextResource
import org.eclipse.xtext.ui.editor.model.IXtextDocument
import org.eclipse.xtext.validation.Check

/**
 * Custom validation rules. 
 *
 * see http://www.eclipse.org/Xtext/documentation.html#validation
 */
class GanttTextValidator extends AbstractGanttTextValidator {
	private static Model m_model;
	private static EList<WorkPackage> m_workPackages;

	def static setActiveDocument(IXtextDocument document) {
		if (document == null) {
			return null
		}
		document.readOnly(
			[ XtextResource resource |
				val obj = resource.allContents.next
				if (obj instanceof Model) {
					m_model = obj as Model
					if (m_model.projects.size > 0 && m_model.projects.get(0).fragmentWorkPackages != null) {
						m_workPackages = m_model.projects.get(0).fragmentWorkPackages.workPackages;
					}
				}
			]);
	}

	@Check
	def checkResourcesAreImplemented(WorkPackageResource workPackageResource) {
		val workPackage = workPackageResource.eContainer.eContainer as WorkPackage
		for (Task task : workPackage.tasks) {
			if (task.providedResources.contains(workPackageResource)) {

				// Resource has been implemented.
				return
			}
		}

		if (m_workPackages != null) {
			for (WorkPackage nestedPackage : m_workPackages) {
				if (workPackage.equals(nestedPackage.packageParent) &&
					nestedPackage.providedResources.contains(workPackageResource)) {

					// Resource has been implemented.
					return
				}
			}
		}

		// WARNING: Resource has *not* been implemented.
		warning(
			"The resource " + workPackageResource.name +
				" has not been implemented by a task or nested work package.",
			GanttTextPackage.Literals.WORK_PACKAGE_RESOURCE__NAME)
	}
}
